// index.js
// 获取应用实例
const app = getApp()
import Toast from '@vant/weapp/toast/toast';
Page({
  data: {
    showLoading:false,//是否显示加载框
    isSHow:false,
    onOff:true,//是否打开提醒
    progressValue: 0,
    tabId:1,
    cardGroup:'CardByTime',//1： 普通 2：时长,
    toAuthMask:false,// 跳转到实名弹窗显示
    restMoney: '',
    cardMsgOk:'',
    cardModel:null,
    listMyCard: [],
    listCharge: [],
    listUsage: [],
    showAlert:false,
    warningMessage:'',
    showPayBox: false,
    paymessage:'',
    functionList:[
        {id:1,name:'交易账单',icon:'deal',img:'../../static/images/zhangdan.png',url:'../../pages/dealInfo/dealInfo'},
        {id:2,name:'交易记录',icon:'charge',img:"../../static/images/record.png",url:"../../pages/charge_record/charge_record"},
        {id:3,name:'服务变更',icon:'exchange',img:"../../static/images/service.png",url:"../../pages/service_exchange/service_exchange"},
        {id:4,name:'停复机',icon:'recovery',img:"../../static/images/off_on.png",url:"../../pages/recovery/recovery"},
        {id:5,name:'客服助手',icon:'helper',img:"../../static/images/ass.png",url:""},
        {id:6,name:'号码绑卡',icon:'bind',img:"../../static/images/band.png",url:"../../pages/bindCard/bindCard"},
    ],
    touchIndex:-1,
    endTime:'',
    total:0,
    remain:0,
    cardId:0,
    today:'',
    isHide:true,
    dtMealByTime:[],
    totalDay:0,
    usedDay:0,
    isAuth: false,
    chargeID:'',
    authDesc:'根据国家规定需进行实名认证后，才可正常使用',
    showAuthBox:false,
    isNeedCharge: false,
    progressValueDay:0,
  },
  /**
   * 生命周期函数--监听页面加载
   */
  handleWarning(){
    if(!this.data.isAuth){
      this.setData({
        showAuthBox:true
      })
      return
    }
    this.SubscribeMessage()
 },
  SubscribeMessage(){
    var that = this;
    wx.requestSubscribeMessage({
      tmplIds: ['5clCjJJApEWnxX0ykFCl-fQVT6gj36J8wxXygHrBib0','Hxk279PkXYG6M3OQ947tWS1eVk-8NuvwKmlLMl7mXuw'],
      success(res) {
        let aa = JSON.stringify(res);
        if (aa.indexOf("accept") > 10) {
          wx.request({
            url: app.globalData.apiUrl + 'Mini/BalCard.ashx?action=14',
            data: {
              userId: that.data.userId
            },
            dataType: 'json',
            header: {
              'content-type': 'application/json'
            },
            success(resroom) {
              var result = resroom.data;
              if (result.getNum == 0) {
                that.setData({
                  onOff: true,
                });
              }
            }
          })
        }
      }
    })
  },
  hideRecovery(cardGroup){
      if(cardGroup === 'CardByTime'){
          const list = this.data.functionList;
          const newList = list.filter(item =>{return item.name !=='停复机' })
          this.setData({
            functionList:newList
          })
      }
  },
  onHide(){
     this.setData({
         isHide: !this.data.isHide
     })
  },
  getTodayDate(){
    var dd = new Date();  
    var y = dd.getFullYear(); 
    var m = dd.getMonth()+1;//获取当前月份的日期 
    var d = dd.getDate(); 
    //判断 月
    if(m < 10){
      m = "0" + m;
    }else{
      m = m;
    }
    //判断 日n     
    if(d < 10){//如果天数<10
      d = "0" + d;
    }else{
      d = d;
    }
    return y+"/"+m+"/"+d; 
  },
  onLoad: function (options) {
    this.selectComponent("#loading").show()
    this.setData({
        today: this.getTodayDate()
    })
    var that = this;
    var cardId = options.cardId;
    if(cardId){
        wx.setStorageSync('cardId', cardId)
    }
    if(wx.getStorageSync('cardId')){
        cardId = wx.getStorageSync('cardId')
    }
  },
  onShow(){
    const that = this;
    app.getLogUser(function (uInfo) {
      const {
        userId,
        userName,
        userOpenId,
        userAvatar
      } = uInfo;
      that.setData({
        userId: userId,
        userName: userName,
        userOpenId: userOpenId,
        userAvatar: userAvatar,
        cardId: wx.getStorageSync('cardId')
      })
      that.getNewInterfaceData()
      that.selectComponent("#loading").hide()
    });
  },
  getNewInterfaceData(){
    const that = this
    wx.request({
        url: app.globalData.apiUrlNew + 'Mini/BalUpdated.ashx?action=main',
        data: {
          cardId:that.data.cardId,
          userId: that.data.userId
        },
        dataType: 'json',
        header: {
          'content-type': 'application/json' // 默认值
        },
        success(resroom) {
          console.log(resroom.data)
          var result = resroom.data;
          if (result.getNum == 0) {
            that.setData({
               objCard: result.objCard,
               cardGroup: result.objCard.cardGroup,
               listCharge: result.dtCharge,
               listUsage: result.dtMealByUsage,
               dtMealByTime: result.dtMealByTime,
               listMyCard: result.dtMyCards,
            });
            if(result.objCard.card_realnamestatus ==2 || result.objCard.card_realnamestatus==3 ){
              that.setData({
                isAuth: true
              })
            }
            that.countRemain(result.objCard)
            that.hideRecovery(result.objCard.cardGroup)
            that.countDay(result.objCard)
          }else if( result.getNum ==10){
            wx.redirectTo({
                url: '../service_choice/service_choice?cardId='+that.data.cardId,
            })
          } else {
              console.log('获取内容失败')
            //   Toast({
            //     type: 'fail',
            //     message: '1' + result.getMsg,
            //     onClose: () => {
            //         wx.redirectTo({
            //             url: '../enter/regMain',
            //         })
            //       },
            //   })
          }
        },
        fail(resfail) {
          Toast.fail(resfail.data)
        }
      }) 
  },
  onChangeAccount(){
    const listMyCard = this.data.listMyCard
    wx.navigateTo({
        url: '../../pages/change_account/change_account',
        success: function(res) {
            // 通过 eventChannel 向被打开页面传送数据
            res.eventChannel.emit('acceptDataFromOpenerPage', { data: listMyCard })
          }
      })
  },
  goCoupon(){
    // 跳转到优惠券页面
    console.log(this.data.objCard)
    wx.navigateTo({
      url: '../coupon/coupon?cardId='+ this.data.objCard.card_id,
    })
  },
  countRemain(cardInfo){
    const usageUsedByCurMonth = cardInfo.usageUsed || 0
    const usageTotalByCurMonth = cardInfo.usageTotal || 0
    if(usageTotalByCurMonth === '不限量'){
        this.setData({
            remain: '不限量',
            progressValue: 2
        }) 
    }else{
        const remain = (usageTotalByCurMonth - usageUsedByCurMonth)/1024
        this.setData({
            remain: `${remain.toFixed(2)}GB`,
            progressValue: usageUsedByCurMonth/usageTotalByCurMonth*100
        })
    }
  },
  countDay(cardInfo){
    const startTime = cardInfo.currentStart || 0;
    const EndTime = cardInfo.currentEnd || 0;
    if(startTime==0 && EndTime==0){
      this.setData({
        totalDay:0,
        usedDay:0,
        progressValueDay:0
      })
    }else{
      const startDay = Date.parse(startTime)
      const endDay = Date.parse(EndTime)
      let  now = Date.now()
      const total = endDay - startDay
      const used = now - startDay
      const totalDay = Math.floor(total / (24 * 3600 * 1000))
      const usedDay = Math.floor(used / (24 * 3600 * 1000))
      const pro = usedDay/totalDay*100
      this.setData({
        totalDay:totalDay,
        usedDay:usedDay,
        progressValueDay: pro
      })
    }
  },
  onTab(e){
    const id = e.currentTarget.dataset.id
    this.setData({tabId:id})
  },
  startTouch(e){
    this.setData({touchIndex:e.currentTarget.dataset.index})
  },
  endTouch(){
    this.setData({touchIndex:-1})
  },
  handleFuntion(e){
    const url = e.currentTarget.dataset.item.url
    const id = e.currentTarget.dataset.item.id
    if(url){
        if(!this.data.isAuth && id != 6){
          this.setData({
            showAuthBox:true
          })
          return
        }
        wx.navigateTo({
            url: url+'?cardId='+ this.data.cardId,
          })
    }else{
        wx.openCustomerServiceChat({
            extInfo: {
              url: 'https://work.weixin.qq.com/kfid/kfca2cc9b204f3791c5'
            },
            corpId: 'ww08696bb5e1f078c3',
            success(res) {}
          })
    }
  },
  //支付功能
  onChargeMoney(e){
    if(!this.data.isAuth){
      this.setData({
        showAuthBox:true
      })
      return
    }
    const proid = e.currentTarget.dataset.charge.pro_id
    this.onQuickCharge(proid)
  },
  //快速充值
  onQuickCharge(proid){
    const that = this
    that.setData({chargeID:''})
    wx.request({
        url: app.globalData.apiUrlNew + 'Mini/BalPayUpdated.ashx?action=charge',
        dataType: "json",
        data: {
          userId: that.data.userId,
          userOpenId: that.data.userOpenId,
          cardId: that.data.cardId,
          mealId: proid
        },
        header: {
          'content-type': 'application/json' // 默认值
        },
        success(resp) {
          var respd = resp.data;
          console.log(respd)
          if (respd.getNum == 0) {
            const {
              timeStamp,
              nonceStr,
              mnpPackage,
              paySign
            } = respd;
            wx.requestPayment({
              nonceStr: nonceStr,
              package: mnpPackage,
              signType: "RSA",
              paySign: paySign,
              timeStamp: timeStamp,
              success: function (resPay) {
              //支付成功
              Toast.success('支付成功')
               
              },
              fail: function (resPay) {
                if (resPay.errMsg == "requestPayment:fail cancel") {
                 // 支付取消
                 that.setData({
                    showAlert:true,
                    warningMessage:'支付失败，你的交易取消',
                 })
                } else {
                    //支付异常
                    wx.redirectTo({
                        url: '../../pages/handle_result/handle_result?resultId=2',
                      })
                }
              },
              complete: function (res) {}
            })
        }else{
          that.setData({
            showAlert:true,
            warningMessage:respd.getMsg,
          })
        }
    },
    fail(e){
      console.log(e)
    }
 })},
  //加油包充值
  onCharge(proid){
    const that = this
    that.setData({chargeID:''})
    wx.request({
        url: app.globalData.apiUrlNew + 'Mini/BalPayUpdated.ashx?action=usagePack',
        dataType: "json",
        data: {
          userId: that.data.userId,
          cardId: that.data.cardId,
          mealId: proid
        },
        header: {
          'content-type': 'application/json' // 默认值
        },
        success(resp) {
          var respd = resp.data;
          console.log(respd)
          if (respd.getNum == 0) {
            const {
              timeStamp,
              nonceStr,
              mnpPackage,
              paySign
            } = respd;
            wx.requestPayment({
              nonceStr: nonceStr,
              package: mnpPackage,
              signType: "RSA",
              paySign: paySign,
              timeStamp: timeStamp,
              success: function (resPay) {
              //支付成功
              Toast.success('支付成功')
              },
              fail: function (resPay) {
                if (resPay.errMsg == "requestPayment:fail cancel") {
                 // 支付取消
                 that.setData({
                    showAlert:true,
                    warningMessage:'支付失败，你的交易取消',
                })
                } else {
                    //支付异常
                    wx.redirectTo({
                        url: '../../pages/handle_result/handle_result?resultId=2',
                      })
                }
              },
              complete: function (res) {}
            })
        }else{
          that.setData({
            showAlert:true,
            warningMessage:respd.getMsg,
          })
        }
    },
    fail(e){
      console.log(e)
    }
 })},
 onServiceCharge(e){
  if(!this.data.isAuth){
    this.setData({
      showAuthBox:true
    })
    return
  }
   let showMsg=''
   const sell = e.currentTarget.dataset.charge.pro_saleprice
   const restMoney = this.data.objCard.bank_rest
   const id = e.currentTarget.dataset.charge.pro_id
   const that = this
   const type = e.currentTarget.dataset.chargetype
  if (parseFloat(restMoney) >= parseFloat(sell)) {
    showMsg = "费用将直接从您的余额中扣除，立即生效，截止于当前周期月的26日，成功后无法退款";
  } else {
    //var payMoney = parseFloat(sell) - parseFloat(restMoney);
    // showMsg = "余额抵扣" + parseFloat(restMoney) + "元，需支付" + payMoney.toFixed(2) + "元，立即生效，截止于当前周期月的26日，成功后无法退款";
    showMsg="余额不足，请立即充值"
    var isNeedCharge = true
  }
  that.setData({
    showPayBox:true,
    paymessage:showMsg,
    chargeID: id,
    chargeType:type,
    isNeedCharge:isNeedCharge
  })
 },
 // 时长包充值
 chargeTime(proid){
  const that = this;
  that.setData({chargeID:''})
  wx.request({
    //url: app.globalData.apiUrl + 'Mini/BalOrder.ashx?action=9',
    url: app.globalData.apiUrl +"Mini/BalPayUpdated.ashx?action=timePack",
    dataType: "json",
    data: {
      userId: that.data.userId,
     // userOpenId: that.data.userOpenId,
      cardId: that.data.cardId,
      mealId: proid
    },
    header: {
      'content-type': 'application/json' // 默认值
    },
    success(resp) {
      var respd = resp.data;
      if (respd.getNum == 5) {
        Toast.success('购买成功')
      } else if (respd.getNum == 0) {
        const {
          timeStamp,
          nonceStr,
          mnpPackage,
          paySign
        } = respd;
        wx.requestPayment({
          nonceStr: nonceStr,
          package: mnpPackage,
          signType: "RSA",
          paySign: paySign,
          timeStamp: timeStamp,
          success: function (resPay) {
            Toast.success('支付成功')
            if(cardMsgOk!=5){
              that.SubscribeMessage();
            }
          },
          fail: function (resPay) {
            if (resPay.errMsg == "requestPayment:fail cancel") {
              // 支付取消
              that.setData({
                showAlert:true,
                warningMessage:'支付失败，你的交易取消',
              })
            } else {
              that.setData({
                showAlert:true,
                warningMessage:resPay.errMsg,
              })
            }
          },
          complete: function (res) {}
        })
      } else {
        Toast.fail("T" + respd.getMsg)
      }
    }
  })
 },
 sureCharge(){
   if(this.data.isNeedCharge) return
   if(this.data.chargeID){
    if(this.data.chargeType == 'usage'){
      this.onCharge(this.data.chargeID)
    }else{
      this.chargeTime(this.data.chargeID)
    }
   }
   
 },
 copy(e){
  const code = e.currentTarget.dataset.code
  wx.setClipboardData({
    data: code,
    success (res) {
      wx.getClipboardData({
        success (res) {
          console.log(res.data) // data
        }
      })
    }
  })
 },
 //实名认证
 authConfirm(){
    const {isAuth,objCard} = this.data;
    if(isAuth) return 
    wx.navigateTo({
      url: '../auth/uploadImg?cardId='+objCard.card_id,
    })
  }
})
